package com.gitee.alpha.ie.convert;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.EnumUtil;
import com.gitee.alpha.framework.core.dict.EnumEntry;
import java.util.LinkedHashMap;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;

/**
 * 支持常量的单元格值转换函数<br>
 *
 * @author 冰羽
 * @version 2.2.0
 */
@Slf4j
public class ConstantCellValueConverter extends SimpleCellValueConverter {

  @Override
  public Object convert(Object o, Class<?> javaType) {
    try {
      // 是否枚举类型
      if (javaType.isEnum() && o != null) {
        String oVal = String.valueOf(o);
        LinkedHashMap constants = EnumUtil.getEnumMap((Class<? extends Enum>) javaType);

        // 值若是Integer，则需要获取到枚举所在的顺序值
        // 值若是String，则匹配Name，或者判断是否为自定义常量类型
        if (CollectionUtil.isNotEmpty(constants)) {
          Set<String> names = constants.keySet();
          for (String name : names) {
            Object val = constants.get(name);
            boolean equals = false;
            // 判断枚举
            if (oVal.equals(name)) {
              equals = true;
            }

            // 判断自定义常量类
            if (equals == false && val instanceof EnumEntry) {
              EnumEntry entry = (EnumEntry) val;
              String label = entry.getLabel();
              if (oVal.equals(label) || oVal.equals(name)) {
                equals = true;
              }
            }

            // 返回值
            if (equals) {
              return constants.get(name);
            }
          }
        }
      }

      return super.convert(o, javaType);
    } catch (Exception e) {
      log.error("cell value convert exception, error: ", e);
    }

    return o;
  }
}
